#!/usr/bin/env python
"""
Sqlite database connection for get / set and in the future 
find and unset functions
"""
import sqlite3 as sql
from os.path import abspath

# import unittest

def db_create(dbname):
    """Creates database for quotes.
       See SQL code...
    """
    conn = sql.connect(dbname)
    query = "create table zaznamy (id integer primary key, key text not null, value text not null)"
    cur = conn.cursor()
    cur.execute(query)
    conn.commit()
    conn.close()


class DbNora(object):
    """Gate to database."""

    def __init__(self, table, dbname = None, key_limit = 15, value_limit = 100):
        self.table = table
        if dbname:
            self.db = sql.connect(abspath(dbname), isolation_level = None)
        # else:
        #    self.db = sql.connect(":memory:")

        self.key_limit = key_limit
        self.value_limit = value_limit


    def db_insert(self, key, value):
        """Inserts pair key - value into table 'zaznamy'."""
        if key and value:
            try:
                cur = self.db.cursor()
                row = tuple([key[:self.key_limit], value[:self.value_limit]])
                query = "insert into zaznamy(key, value) values (?,?)"
                cur.execute(query, row)
                self.db.commit()
            except sql.DatabaseError:
                raise IOError("Chyba pri vkladani dat.")

    def db_select(self, key):
        """Selects from table 'zaznamy'."""
        try:
            curr = self.db.cursor()

            query = "select value from zaznamy where key = ? order by id"
            curr.execute(query, (key[:self.key_limit],))

            res = ""
            cnt = 1
            temp = curr.fetchall()
            if temp:
                for item in temp:
                    res += "\n[%d] %s" % (cnt, item[0],)
                    cnt += 1
            else:
                res = "Sorry, toto heslo nepoznam."

            return res
        except sql.DatabaseError:
            pass

    def db_delete(self, key, id_ = None):
        """Not implemented."""
        try:
            cur = self.db.cursor()
            if id_:
                # vyberieme zaznamy s pozadovanym klucom
                match = cur.execute("select id from zaznamy where key = ?",
                                    ([key])).fetchall()
                if not match:
                    raise KeyError("Zaznam neexistuje.")
                if len(match) < id_ or id_ < 1:
                    raise IndexError("Co to mam zmazat? Este raz si pozri cislo. ;)")
                # zostavime query
                query = "delete from zaznamy where id = ?"
                # a hadam to funguje ako ma :D
                cur.execute(query, (match[id_ - 1]))
            else:
                # lepsie by asi bolo count ...
                tmp = cur.execute("select * from zaznamy where key = ?", ([key])).fetchall()
                if len(tmp) == 0:
                    raise KeyError("Zaznam neexistuje.")
                query = "delete from zaznamy where key = ?"
                cur.execute(query, ([key]))
            self.db.commit()
        except (sql.DatabaseError), err:
            raise Error(err)
        
#class _DbNoraTest(unittest):
#    pass

if __name__ == "__main__":
    pass

